import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:ota_update/ota_update.dart';
import 'package:umeng_common_sdk/umeng_common_sdk.dart';
import 'package:http/http.dart' as http;
import 'package:yysc_flutter/util/ApiService.dart';

class CommonUtils {
  /// 注册友盟
  static initUmeng(String androidAppkey,String iosAppKey) {
    UmengCommonSdk.initCommon(
        androidAppkey, iosAppKey, 'Umeng');
    UmengCommonSdk.setPageCollectionModeManual();
  }

  /// 检测更新版本信息
  static Future<void> check(
      String version, ValueChanged<String> callback) async {
    final response = await http.post(
      Uri.parse('http://movie.igomall.xin/api/check?version=$version'),
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
      },
    );
    if (response.statusCode == 200) {
      String responseBody = utf8.decode(response.bodyBytes);
      callback(responseBody);
    } else {
      print(response.statusCode);
    }
  }

  static Future<void> tryOtaUpdate(
      String url, ValueChanged<String> callback) async {
    try {
      OtaUpdate()
          .execute("http://file.igomall.xin/xiaocha.apk",
              destinationFilename: 'xiaocha.apk')
          .listen(
        (OtaEvent event) {
          callback(event.value!);
        },
      );
    } catch (e) {
      print('Failed to make OTA update. Details: $e');
    }
  }

  static void showUpdateDialog(
      BuildContext context, String url, ValueChanged<String> callback) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('提醒'),
          content: const Text('发现新版本，是否立即更新。'),
          actions: <Widget>[
            OutlinedButton(
              style: ButtonStyle(
                minimumSize: WidgetStateProperty.all(const Size(1, 1)),
                padding: WidgetStateProperty.all<EdgeInsets>(
                    const EdgeInsets.symmetric(vertical: 8, horizontal: 24)),
              ),
              child: const Text('关闭'),
              onPressed: () {
                Navigator.of(context).pop(); // 关闭对话框
              },
            ),
            FilledButton(
              style: ButtonStyle(
                backgroundColor:
                    WidgetStateProperty.all<Color>(Color(0xff4f59fd)),
                minimumSize: WidgetStateProperty.all(const Size(1, 1)),
                padding: WidgetStateProperty.all<EdgeInsets>(
                    const EdgeInsets.symmetric(vertical: 8, horizontal: 24)),
              ),
              child: const Text('立即更新'),
              onPressed: () {
                CommonUtils.tryOtaUpdate(url, (rate) {
                  callback(rate);
                });
                Navigator.of(context).pop(); // 关闭对话框
              },
            ),
          ],
        );
      },
    );
  }

  // 检测更新版本信息
  static Future<void> getConfig(ValueChanged<Map<String, dynamic>> callback) async {
    ApiService().post("/config").then((res){
      callback(res.data);
    });
  }
}
